/**
 * 尊敬的用户，你好：页面 JS 面板是高阶用法，一般不建议普通用户使用，如需使用，请确定你具备研发背景，能够自我排查问题。
 * 我们可以用 JS 面板来开发一些定制度高功能，比如：调用API接口，自定义动作执行等等。
 */

// 当页面渲染完毕后马上调用下面的函数，这个函数是在当前页面 - 设置 - 生命周期 - 页面加载完成时中被关联的。
export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);
    addStyle();
    const textElm1 = this.$$('text_4gasno');

    const ddcatSources = [
        {id: "ds_mod:4c0b2058-a01d-4a78-a0a6-50cc80d226e2", name: "临时检查-高频临时检查"}
    ];

    fetchDdcatData(ddcatSources[0].id).then(res => {
        debugger
        addHTML(textElm1, res);
    });
}

// 添加样式
function addStyle() {
    const css = `
        .situation-use-container {
            width: 100%;
            overflow: hidden;
        }

        #usageList {
            height: 100%;
            overflow-y: auto;
        }

        #usageList::-webkit-scrollbar {
            width: 6px;
        }

        #usageList::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 3px;
        }

        .situation-use-bar-container {
            margin-bottom: 10px;
        }

        .situation-use-bar-header {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            margin-bottom: 4px;
        }

        .situation-use-bar {
            height: 10px;
            border-radius: 5px;
            background-color: #eee;
            overflow: hidden;
            position: relative;
        }

        .situation-use-bar-fill {
            height: 100%;
            background: #3388FF;
            border-radius: 5px;
            position: absolute;
            left: 0;
            top: 0;
            transition: width 0.8s ease;
        }
    `;

    const style = document.createElement("style");
    style.innerHTML = css;
    style.id = "situationUseStyles";
    document.head.appendChild(style);
}

// 插入HTML并监听变化
function addHTML(textElm1, data) {
    const str = `
    <div class="situation-use-container">
        <div id="usageList"></div>
    </div>
    `;

    const targetNode = textElm1.$el;
    const config = {childList: true, subtree: true};

    const observer = new MutationObserver(function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                renderData(data);
                observer.disconnect();
                break;
            }
        }
    });

    observer.observe(targetNode, config);
    textElm1.$$setValue(str);
}

// 渲染进度条数据
function renderData(rawData) {
    const usageList = document.getElementById("usageList");
    if (!usageList) return;

    let processedData = [];

    processedData = rawData
        .map(d => ({
            name: d.name || '未知部门',
            count: Number(d.count || 0)
        }))
        .sort((a, b) => b.count - a.count)
        .slice(0, 10);

    let maxCount = 1;
    for (let i = 0; i < processedData.length; i++) {
        if (processedData[i].count > maxCount) {
            maxCount = processedData[i].count;
        }
    }

    usageList.innerHTML = "";

    processedData.forEach((item, idx) => {
        const barWidth = (item.count / maxCount) * 100;
        const bar = document.createElement("div");
        bar.className = "situation-use-bar-container";
        bar.innerHTML = `
            <div class="situation-use-bar-header">
                <span>${idx + 1}. ${item.name}</span>
                <span>${item.count}</span>
            </div>
            <div class="situation-use-bar">
                <div class="situation-use-bar-fill" style="width:${barWidth}%"></div>
            </div>
        `;
        usageList.appendChild(bar);
    });
}

function fetchDdcatData(sourceId) {
    const jsonParams = {pageSize: 99999};
    return api.DATA_SOURCE_EXECUTE(
        sourceId,
        "ddcat",
        [],
        [],
        JSON.stringify(jsonParams)
    ).then(res => {
        if (res && !res.hasError && res.result) {
            return res.result;
        } else {
            console.warn("查询失败", res);
            return generateMockData();
        }
    });
}

function generateMockData() {
    const mockData = [];
    for (let i = 1; i <= 10; i++) {
        mockData.push({
            name: `部门${i}`,
            count: Math.floor(Math.random() * 100) + 1 // 随机生成1到100之间的数字
        });
    }
    return mockData;
}
